<script setup lang="tsx">
import { ref, computed, onMounted, watch } from 'vue'
import { orderApi } from '@/api/logistics/waybill'
import { searchStoreApi } from '@/api/utils/search'
import {
  ElTable,
  ElTableColumn,
  ElPagination,
  ElInput,
  ElSelect,
  ElOption,
  ElButton
} from 'element-plus'
const props = defineProps({
  currentRow: {
    type: Object,
    default: () => ({})
  }
})
const from = ref({
  store_id: '',
  no: ''
})

const options = ref([{ id: '', name: '' }])

interface Detail {
  id: number
  goods_name: string
  goods_spec_name: string
  quantity: string
  income: string
  amount: string
}

interface Order {
  id: number
  no: string
  count: number
  detail: Detail[]
}

interface Store {
  store_id: number
  store_name: string
  detail: Order[]
}

const data = ref([])

const pageSize = ref(1000)
const currentPage = ref(1)
const count = ref(0)

onMounted(() => {
  getOrDerApi()
  getSearchStoreApi()
})

// 门店检索框
const getSearchStoreApi = async () => {
  const res = await searchStoreApi({ field: 'id,name' })
  options.value = res.data.list
}

// 表格数据
const getOrDerApi = async () => {
  const res = await orderApi({
    page: currentPage.value,
    limit: pageSize.value,
    deliver_task_id: props.currentRow.id,
    store_id: from.value.store_id,
    no: from.value.no
  })
  data.value = res.data.list
  count.value = res.data.count
}
// 重置
const Reset = () => {
  from.value.store_id = ''
  from.value.no = ''
  getOrDerApi()
}

// Flatten the data for table display
const flattenData = (stores: Store[]) => {
  return stores.flatMap((store) =>
    store.detail.flatMap((order) =>
      order.detail.map((detail) => ({
        store_name: store.store_name,
        no: order.no,
        count: order.count,
        detail_id: detail.id,
        goods_name: detail.goods_name,
        goods_spec_name: detail.goods_spec_name,
        quantity: detail.quantity,
        income: detail.income,
        amount: detail.amount
      }))
    )
  )
}

const currentData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return flattenData(data.value).slice(start, end)
})

const handleSizeChange = (size: number) => {
  pageSize.value = size
  getOrDerApi()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getOrDerApi()
}

const mergeCells = ({ row, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    // Merge cells for store_name
    if (rowIndex === 0 || row.store_name !== currentData.value[rowIndex - 1].store_name) {
      let rowspan = 1
      for (let i = rowIndex + 1; i < currentData.value.length; i++) {
        if (row.store_name === currentData.value[i].store_name) {
          rowspan++
        } else {
          break
        }
      }
      return {
        rowspan,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  } else if (columnIndex === 1) {
    // Merge cells for no
    if (rowIndex === 0 || row.no !== currentData.value[rowIndex - 1].no) {
      let rowspan = 1
      for (let i = rowIndex + 1; i < currentData.value.length; i++) {
        if (row.no === currentData.value[i].no) {
          rowspan++
        } else {
          break
        }
      }
      return {
        rowspan,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  } else if (columnIndex === 2) {
    // Merge cells for count
    if (rowIndex === 0 || row.count !== currentData.value[rowIndex - 1].count) {
      let rowspan = 1
      for (let i = rowIndex + 1; i < currentData.value.length; i++) {
        if (row.count === currentData.value[i].count) {
          rowspan++
        } else {
          break
        }
      }
      return {
        rowspan,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
  return {
    rowspan: 1,
    colspan: 1
  }
}
</script>
<template>
  <div style="width: 100%; display: flex; align-items: center; margin: 10px 0">
    <div style="margin-right: 10px">
      <span>配送门店：</span>
      <el-select v-model="from.store_id" placeholder="请选择" style="width: 200px">
        <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
    </div>
    <div style="margin-right: 10px">
      <span>关联订单号：</span>
      <el-input v-model="from.no" style="width: 200px" placeholder="请输入" />
    </div>
    <div style="margin-right: 10px">
      <el-button type="primary" @click="getOrDerApi()">搜索</el-button>
    </div>
    <div>
      <el-button type="info" @click="Reset()">重置</el-button>
    </div>
  </div>
  <div>
    <el-table :data="currentData" border style="width: 100%" :span-method="mergeCells">
      <el-table-column prop="store_name" label="配送门店" />
      <el-table-column prop="no" label="关联订单号" />
      <el-table-column prop="count" label="品类数量" />
      <el-table-column prop="goods_name" label="商品" />
      <el-table-column prop="goods_spec_name" label="规格" />
      <el-table-column prop="quantity" label="数量" />
      <el-table-column prop="amount" label="订单金额（元）" />
      <el-table-column prop="income" label="配送收益" />
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="count"
      style="margin-top: 20px"
    />
  </div>
</template>
